// pages/takephoto/takephoto.js
import Dialog from 'vant-weapp/dialog/dialog';
const uploadImage = require('../../utils/uploadFile.js');
const client = require("../../utils/client.js");
const app = getApp()
const body = require('../../utils/bodyBusiness.js')
const model = require('../../utils/modelBusiness.js');
const classify = require('../../utils/classify.js');
const canvasWebGLId = 'canvasWebGL';
// throttling
const cameraFrameMax = 6;
// a url of gltf model 
const modelUrl = 'https://m.sanyue.red/demo/imgs/cat_beard.png';
// camera listener
var listener = null;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showTime: false,
    time: 3,
    showToast: false,
    device: 'back',
    showsrc: false,
    type: 1,
    showoverlay: true,
    d_type: 0,
    cannet: true,
    cannext: true,
  },
  chengcamera() {
    // wx.navigateTo({
    //   url: '/pages/takepuserhone/takepuserhone',
    // })
    // return
    this.setData({
      device: this.data.device == 'back' ? 'front' : 'back'
    })
    if (this.data.device === 'front') {
      wx.showModal({
        title: '提示',
        showCancel: 'false',
        content: '请按照图示摆好姿势后将自动拍摄',
        complete: (res) => {
          if (res.cancel) {
            this.getbodyVKSession()
          }
        }
      })
    }
  },

  //点位计算
  initBodyDetect_callback(predictions, detect_time) {
    var _that = this

    if (predictions && predictions.length > 0) {
      var prediction = predictions[0]
      // // 23个关键点
      // let gesture = []
      // for (let i = 0; i < 23; i++) {
      //   const point = prediction.points[i]
      //   // 归一化数值
      //   const gesture_x = point.x - prediction.origin.x
      //   const gesture_y = point.y - prediction.origin.y

      //   gesture.push([parseFloat(gesture_x.toFixed(2)),
      //     parseFloat(gesture_y.toFixed(2))
      //   ])
      // }
      //胸口
      var breast = predictions[0].points[14]
      //手
      var lefthead = predictions[0].points[18]
      var righthead = predictions[0].points[17]
      //手肘
      var leftwrist = predictions[0].points[8]
      var rightwrist = predictions[0].points[7]
      //臀部
      var leftbuttocks = predictions[0].points[12]
      var rightbuttocks = predictions[0].points[11]
      //脚
      var leftfoot = predictions[0].points[20]
      var rightfoot = predictions[0].points[21]
      //人体是否入镜
      var isbody = true
      //置信度


      // console.log(predictions[0].points3d,'3D坐标点位')
      // console.log(predictions[0].origin,'起始点位')
      // console.log(predictions[0].size.width, predictions[0].size.height, '识别框大小')
      if (predictions[0].size.width > 0.8 || predictions[0].size.height > 0.8) {
        console.log('----------人物未全部入境-------------')
        return
      }
      if (this.data.showToast) {
        return
      }
      if (this.data.device === 'back') {
        return
      }

      if(!this.data.cannet){
        return
      }
      var footwidth = Math.abs(Math.abs(predictions[0].points3d[11].x) - Math.abs(predictions[0].points3d[12].x))
      var footheight = Math.abs(Math.abs(predictions[0].points3d[11].y) - Math.abs(predictions[0].points3d[12].y))
      var footzzhou = Math.abs(Math.abs(predictions[0].points3d[11].z) - Math.abs(predictions[0].points3d[12].z))
      // console.log(footwidth,'双脚X轴间距')
      // console.log(footheight,'双脚Y轴落差')
      // console.log(footzzhou,'双脚Z轴落差')
      var hadewidth = Math.abs(Math.abs(predictions[0].points3d[23].x) - Math.abs(predictions[0].points3d[22].x))
      var hadeheight = Math.abs(Math.abs(predictions[0].points3d[23].y) - Math.abs(predictions[0].points3d[22].y))
      var hadezzhou = Math.abs(Math.abs(predictions[0].points3d[23].z) - Math.abs(predictions[0].points3d[22].z))
      // console.log(hadewidth,'双手X轴间距')
      // console.log(hadeheight,'双手Y轴间距')
      // console.log(hadezzhou,'双手Z轴间距')
      var hadejuli = lefthead.x - righthead.x
      var hadegaodu = lefthead.y - righthead.y
      // console.log(hadejuli,'2D手X轴间距')
      // console.log(hadegaodu,'2D双脚Y轴间距')
      var lefthadeandchest = Math.abs(Math.abs(predictions[0].points[10].y) - Math.abs(predictions[0].points[6].y))
      var righthadeandchest = Math.abs(Math.abs(predictions[0].points[9].y) - Math.abs(predictions[0].points[5].y))
      // console.log(lefthadeandchest,'2D左手手腕跟胸水平差距')
      // console.log(righthadeandchest,'2D右手手腕跟胸水平差距')
      // console.log('----------平面距离-------------')
      if (Math.abs(hadejuli) > 0.5 & Math.abs(hadegaodu) < 0.01 & lefthadeandchest < 0.01 & lefthadeandchest < 0.01) {
        console.log('----------双手已张开-------------')
        const _this = this
        if(!_this.data.cannext){
          return
        }
        _this.daojishi()
      }
    }
    console.log(Math.abs(hadejuli),Math.abs(hadegaodu),lefthadeandchest,righthadeandchest,'点位计算')
    if(Math.abs(hadejuli) < 0.01 & Math.abs(hadegaodu) < 0.01 & lefthadeandchest > 0.15 & righthadeandchest > 0.15){
      console.log('----------人物已站直-------------')
      const _this = this
      if(!_this.data.cannext){
        return
      }
        _this.daojishi()
    }
  },
  //倒计时
  daojishi() {
    var _this = this
    body.stopStop();
    _this.setData({
      showTime: true,
      cannext: false,
      time: 3,
      cannet: false
    })
    var timeoutId = null;
    timeoutId = setInterval(function () {
      console.log(_this.data.time,'----------倒计时--------')
      _this.setData({
        time: _this.data.time - 1
      })
    }, 1000);
    setTimeout(() => {
      _this.camera()
      _this.setData({
        showTime: false,
        cannet: true,
        time: 3
      })
      clearTimeout(timeoutId)
    }, 3500);
  },
  startTacking() {
    var _that = this;
    var count = 0;
    const context = wx.createCameraContext();

    // real-time
    listener = context.onCameraFrame(function (res) {
      // this is throttling
      if (count < cameraFrameMax) {
        count++;
        return;
      }
      count = 0;
      const frame = {
        // the data type is ArrayBuffer
        data: res.data,
        width: res.width,
        height: res.height,
      };
      _that.frameWidth = frame.width
      _that.frameHeight = frame.height

      // process
      body.bodyDetect(frame, 0);
    });
    // start
    listener.start();
    console.log('startTacking', 'listener is start');
  },
  //上传到阿里云
  upHeadImg(img) {
    console.log(img, '传入图片')
    var that = this
    uploadImage(img, `wms-prod2024/`,
      function (res) {
        console.log(res, '上传图片')
        client.callRecognizeBankCard(wx, res, function (result) {
          console.log(result.Data.PersonNumber, '输出结果')
          if (result.Data.PersonNumber !== 1) {
            wx.hideLoading()
            wx.showModal({
              title: '警告',
              content: '你去哪了？换个光线均匀，背景干净的地方再试一下吧！',
              showCancel: 'false',
              complete: (res) => {
                if (res.cancel) {

                }
              }
            })
            return
          } else {
            wx.hideLoading()
            switch (that.data.type) {
              case 1:
                wx.hideLoading()
                that.setData({
                  frontImgUrl: res,
                  type: 2,
                  showsrc: false,
                  showoverlay: true,
                  d_type: 2
                })
                break;
              case 2:
                wx.hideLoading()
                that.setData({
                  sideImgUrl: res,
                  type: 3,
                  showsrc: false,
                  showoverlay: true,
                  d_type: 3
                })
                break;
              case 3:
                wx.hideLoading()
                that.setData({
                  backImgUrl: res,
                })
                var item = {
                  frontImgUrl: '',
                  sideImgUrl: '',
                  backImgUrl: '',
                }
                item.frontImgUrl = that.data.frontImgUrl
                item.sideImgUrl = that.data.sideImgUrl
                item.backImgUrl = that.data.backImgUrl
                console.log(item)
                wx.setStorageSync('userdate', item)
                wx.navigateTo({
                  url: '/pages/index/index',
                })
                break;
              default:
                break;
            }
          }
        }.bind(this));
      },
      function (res) {
        console.log(res, '上传失败')
        wx.hideLoading()
      }
    )
  },
  //点击拍摄
  camera() {
    console.log(this.data.x, this.data.z, '倾斜角度判定')
    console.log(11111)
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        console.log(res)
        switch (this.data.type) {
          case 1:
            this.setData({
              showsrc: false,
              src_1: res.tempImagePath,
              showsrc: true,
            })
            break;
          case 2:
            this.setData({
              showsrc: false,
              src_2: res.tempImagePath,
              showsrc: true
            })
            break;
          case 3:
            this.setData({
              src_3: res.tempImagePath,
              showsrc: true
            })
            break;
          default:
            break;
        }
      }
    })
  },
  error(e) {
    console.log(e.detail)
  },
  selectImg() {
    // if (!this.data.showToast) {
    //   return
    // }
    var that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      camera: 'back',
      success(res) {

        console.log(res)
        switch (that.data.type) {
          case 1:
            that.setData({
              showsrc: false,
              src_1: res.tempFiles[0].tempFilePath,
              showsrc: true,
            })
            break;
          case 2:
            that.setData({
              showsrc: false,
              src_2: res.tempFiles[0].tempFilePath,
              showsrc: true
            })
            break;
          case 3:
            that.setData({
              src_3: res.tempFiles[0].tempFilePath,
              showsrc: true
            })
            break;
          default:
            break;
        }
      }
    })
  },
  //重新拍摄
  return () {
    const _this = this
    body.initBodyDetect(_this.initBodyDetect_callback);
    _this.setData({
      src: '',
      showsrc: false,
      cannext: true,
    })
  },
  //点击上传
  upload() {
    const _this = this
    body.initBodyDetect(_this.initBodyDetect_callback);
    _this.setData({
      cannext: true
    })
    switch (_this.data.type) {
      case 1:
        wx.showLoading({
          title: '上传中...',
        })
        _this.upHeadImg(_this.data.src_1)
        break;
      case 2:
        wx.showLoading({
          title: '上传中...',
        })
        _this.upHeadImg(_this.data.src_2)
        break;
      case 3:
        wx.showLoading({
          title: '上传中...',
        })
        _this.upHeadImg(_this.data.src_3)
        break;
      default:
        break;
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.iazhanting){
      wx.setNavigationBarTitle({
        title: 'AI量体',
      })
      wx.setStorageSync('iazhanting', true)
    }else{
      wx.setStorageSync('iazhanting', false)
    }
    const _this = this
    var _that = this;
    body.initBodyDetect(_that.initBodyDetect_callback);
    // load a 3D model
    model.initThree(canvasWebGLId, modelUrl);

    // init gesture data
    classify.initGestureData()

    // start camera tracking
    _that.startTacking();
    //陀螺仪检测
    wx.startGyroscope({
      interval: 'normal',
      success(res) {
        console.log(res, '陀螺仪')
        wx.onAccelerometerChange((result) => {
          _this.setData({
            x: Math.abs(result.x),
            y: Math.abs(result.y),
            z: Math.abs(result.z)
          })
          var x = result.x
          var y = result.y
          var z = result.z

          var Pitch = Math.atan2(y, z) * 180 / Math.PI
          var Roll = Math.atan2(-x, Math.sqrt(y * y + z * z)) * 180 / Math.PI
          if (Math.abs(Pitch) > 110 || Math.abs(Pitch) < 70 || Math.abs(Roll) > 8) {
            _this.setData({
              showToast: true
            })
          } else {
            _this.setData({
              showToast: false
            })
          }
        })
      },
    })
    _this.setData({
      type: 1,
      d_type: 0,
    })
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.camera']) {
          // 用户已经授权
          _this.setData({
            isAuth: true
          })
        } else {
          // 用户还没有授权，向用户发起授权请求
          wx.authorize({
            scope: 'scope.camera',
            success() { // 用户同意授权
              _this.setData({
                isAuth: true
              })
            },
            fail() { // 用户不同意授权
              Dialog.alert({
                title: '提示',
                message: '授权失败，请打开相机授权！！',
              }).then(() => {
                wx.openSetting({
                  success(res) {
                    _this.onLoad()
                  }
                })
              });
              // wx.navigateBack({
              //   data: 1
              // })
            }
          })
        }
      },
      fail: res => {
        console.log('获取用户授权信息失败')
      }
    })
  },
  hideshow() {
    switch (this.data.d_type) {
      case 0:
        var volumeJson = wx.getStorageSync('volumeJson')
        console.log(volumeJson,'判断量体数据')
        if(wx.getStorageSync('iazhanting')){
          volumeJson = {}
        }
        if (volumeJson) {
          this.setData({
            showoverlay: false
          })
          Dialog.confirm({
              title: '提示',
              message: '您已拍照测量过量体数据，是否需要重新测算？',
              confirmButtonText: '查看',
              cancelButtonText: '重测'
            })
            .then(() => {
              wx.redirectTo({
                url: '/pages/consequence/consequence',
              })
            })
            .catch(() => {
              this.setData({
                d_type: 1,
                showoverlay: true
              })
            });
        } else {
          this.setData({
            d_type: 1
          })
        }
        break;
      case 1:
        this.setData({
          showoverlay: false
        })
        break;
      case 2:
        this.setData({
          showoverlay: false
        })
        break;
      case 3:
        this.setData({
          showoverlay: false
        })
        break;
      default:
        break;
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    //this.getbodyVKSession()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    //this.stopTacking();
    console.log('onUnload', 'The listener is stop.');

    body.stopBodyDetect();
    model.stopAnimate();
    model.dispose();

    classify.dispose()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})